<!--外来人员入厂-->
<template>
   
    <van-form @submit="onSubmit">
        {{ sfzfh }}
        <h2 class="van-doc-demo-block__title">请选择您的入厂类型</h2>

        <van-cell-group inset>
            <!-- 入厂类型 -->
            <van-field v-model="income" is-link name="incomePicker" label="入厂类型" placeholder="点击选择入厂类型" required
                @click="incomePicker = true" :rules="[{ required: true, message: '入厂类型' }]" />
            <van-popup v-model:show="incomePicker" position="bottom">
                <van-picker :columns="incomeColumns" @confirm="onIncomeConfirm" @cancel="incomePicker = false" />
            </van-popup>

        </van-cell-group>

        <h2 class="van-doc-demo-block__title">请填写您要拜访的人员信息</h2>

        <van-cell-group inset>
            <!-- 厂区 -->
            <van-field v-model="factory" is-link name="factoryPicker" label="厂区" placeholder="点击选择厂区" required
                @click="factoryPicker = true" />
            <van-popup v-model:show="factoryPicker" position="bottom">
                <van-picker :columns="factoryColumns" @confirm="onFactoryConfirm" @cancel="factoryPicker = false" />
            </van-popup>
            <!-- 部门 -->
            <van-field v-model="section" is-link name="sectionPicker" label="部门" placeholder="点击选择部门" required
                @click="sectionPicker = true" :rules="[{ required: true, message: '部门' }]" />
            <van-popup v-model:show="sectionPicker" position="bottom">
                <van-picker :columns="sectionColumns" @confirm="onSectionConfirm" @cancel="sectionPicker = false"
                    v-model="departmentValue" />
            </van-popup>
            <!-- 姓名 -->
            <van-field v-model="sqr" is-link name="sqr" label="姓名" placeholder="姓名" required @click="sqrPicker = true"
                :rules="[{ required: true, message: '姓名' }]" />
            <van-popup v-model:show="sqrPicker" position="bottom">
                <van-picker :columns="sqrColumns" @confirm="onSqrConfirm" @cancel="sqrPicker = false" />
            </van-popup>
        </van-cell-group>
        <h2 class="van-doc-demo-block__title">来访信息</h2>

        <van-cell-group inset>
            <!-- 来访人姓名 -->
            <van-field v-model="comeName" name="comeName" label="来访者姓名" placeholder="来访者姓名" required
                :rules="[{ required: true, message: '来访者姓名' }]" />
            <!-- 联系电话 -->
            <van-field v-model="tel" name="tel" label="联系电话" placeholder="联系电话" required
                :rules="[{ required: true, message: '联系电话' }]" />
            <!-- 来访单位 -->
            <van-field v-model="comeUnit" name="comeUnit" label="来访单位" placeholder="来访单位" required
                :rules="[{ required: true, message: '来访单位' }]" />
            <!-- 来访事由 -->
            <van-field v-model="comeMatter" name="comeMatter" label="来访事由" placeholder="来访事由" required
                :rules="[{ required: true, message: '来访事由' }]" />
            <!-- 入厂时间 -->
            <van-field v-model="enterFactoryTime" is-link name="comeTimePicker" label="入厂时间" placeholder="入厂时间"
                @click="comeTimePicker = true" />
            <van-popup v-model:show="comeTimePicker" position="bottom">
                <van-picker-group title="入厂时间" :tabs="['选择日期', '选择时间']" @confirm="comeTimeConfirm"
                    @cancel="comeTimePicker = false">
                    <van-date-picker v-model="cometDate" :min-date="minDate" :max-date="maxDate" />
                    <van-time-picker v-model="comeTime" />
                </van-picker-group>
            </van-popup>
            <!-- 离厂时间 -->
            <van-field v-model="leaveFactoryTime" is-link name="leaveTimePicker" label="离厂时间" placeholder="离厂时间"
                @click="leaveTimePicker = true" />
            <van-popup v-model:show="leaveTimePicker" position="bottom">
                <van-picker-group title="离厂时间" :tabs="['选择日期', '选择时间']" @confirm="leaveTimeConfirm"
                    @cancel="leaveTimePicker = false">
                    <van-date-picker v-model="leaveDate" :min-date="minDate" :max-date="maxDate" />
                    <van-time-picker v-model="leaveTime" />
                </van-picker-group>
            </van-popup>
            <!-- 同行人 -->
            <van-field v-model="associated" name="associated" label="同行人" placeholder="同行人" />
            <!-- 身份证号码 -->
            <van-field v-model="sfzhm" name="sfzhm" label="身份证号码" placeholder="身份证号码" v-show="sfzPicker" required />
            <!-- 身份证上传 -->
            <van-field name="uploader" label="身份证上传" v-show="sfzPicker">
                <template #input>
                    <van-uploader :before-delete="sfzdelete" :before-read="beforeRead" v-model="sfz"
                        :after-read="afterRead" />
                </template>
            </van-field>
            <!-- 驾车入厂 -->
            <!-- <van-field name="driving" label="驾车入厂" @click="driveClick" required>
                <template #input>
                    <van-radio-group v-model="checked" direction="horizontal">
                        <van-radio name="1">是</van-radio>
                        <van-radio name="2">否</van-radio>
                    </van-radio-group>
                </template>
            </van-field> -->
            <!-- 车牌号 -->
            <van-field v-show="platePicker" v-model="licenseNum" name="licenseNum" label="车牌号" placeholder="车牌号" />
            <!-- 物资名称 -->
            <van-field v-show="platePicker" v-model="goods" name="goods" label="物资名称" placeholder="物资名称" />
        </van-cell-group>
        <div style="margin: 16px;">
            <van-button round block type="primary" native-type="submit">
                提交
            </van-button>
        </div>
    </van-form>

</template>
<script>

import { onMounted, ref } from 'vue';
import { request } from "../../utils/request";
import { showToast, showLoadingToast, closeToast } from 'vant';

import { useRouter } from 'vue-router'

export default {
    setup() {

        onMounted(() => {
            //组件挂载的过程 包括数据 dom等
            getDepartMent();
        });
        const getDepartMent = () => {
            let department = [];
            request({
                url: `/wui/jzhb/visitor_svc2.jsp`,
                method: "get",
            }).then((res) => {
                res.forEach(element => {
                    department.push(
                        { text: element.dname, value: element.did, emps: element.emps }
                    )
                });
                sectionColumns.value = department;

            });
        }
        let sfzfh = ref('');
        // 厂区
        const factoryColumns = ref([
            { text: '金正厂区', value: '0' },
            { text: '水环境', value: '1' },
        ]);
        const factory = ref('金正厂区');
        let factoryValue = '0';
        const factoryPicker = ref(false);

        // 入厂类型
        const incomeColumns = ref([
            { text: '客户来访', value: '0' },
            { text: '其它来访', value: '1' },
            { text: '物资运输', value: '2' },
        ]);
        const income = ref('');
        let incomeValue = '';
        const incomePicker = ref(false);
       
        // 部门
        const section = ref('');
        const sectionPicker = ref(false);
        const sectionColumns = ref({});
        let departmentValue = ref([]);


        // 姓名(申请人)
        const sqr = ref('');
        const sqrPicker = ref(false);
        let sqrColumns = ref([]);
        let sqrValue = '';


        // 车牌号
        let platePicker = ref(false);
        const licenseNum = ref('');

        // 物资名称
        const goods = ref('');

        // 驾车入厂
        // const checked = ref('');

        // 入厂时间
        const comeTimePicker = ref(false);
        const comeDate = ref(['2022', '06', '01']);
        const comeTime = ref(['12', '00']);
        let enterFactoryTime = ref('');

        // 离厂时间
        const leaveTimePicker = ref(false);
        const leaveDate = ref(['2022', '06', '01']);
        const leaveTime = ref(['12', '00']);
        let leaveFactoryTime = ref('');

        let comeName = ref('');

        let comeUnit = ref('');

        let sfzhm = ref('')

        let tel = ref('');

        let associated = ref('');

        let comeMatter = ref('');
        // 跳转到新增扶持页面
        3
        const $router = useRouter();

        // 身份证默认值
        const sfzPicker = ref(false);
        const sfz = ref([
            // { url: 'https://fastly.jsdelivr.net/npm/@vant/assets/leaf.jpeg' },
        ]);

        //厂区选择
        const onFactoryConfirm = ({ selectedOptions }) => {
            factory.value = selectedOptions[0]?.text;
            factoryValue = selectedOptions[0]?.value;
            factoryPicker.value = false;
        };

        //入厂类型选择
        const onIncomeConfirm = ({ selectedOptions }) => {
            income.value = selectedOptions[0]?.text;
            incomeValue = selectedOptions[0]?.value;
            if (incomeValue == '0') {
                // alert("客户来访")
                sfzPicker.value = false
            } else {
                sfzPicker.value = true
            }
            if (incomeValue == '1') {
                // alert("其它来访")
            }
            if (incomeValue == '2') {
                // alert("物资运输")
                platePicker.value = true;
            } else {
                platePicker.value = false;
            }
            incomePicker.value = false;
        };

        //部门选择
        const onSectionConfirm = ({ selectedOptions }) => {
            section.value = selectedOptions[0]?.text;
            departmentValue = selectedOptions[0]?.value;
            var emps = selectedOptions[0]?.emps;
            sqrColumns.value = [];
            emps.forEach(v => {
                sqrColumns.value.push({ text: v.ename, value: v.eid })
            })
            sectionPicker.value = false;
        };


        //姓名选择
        const onSqrConfirm = ({ selectedOptions }) => {
            sqr.value = selectedOptions[0]?.text;
            sqrValue = selectedOptions[0]?.value;
            // console.log(sqrValue)
            sqrPicker.value = false;
        };

        //入厂时间
        const comeTimeConfirm = () => {
            enterFactoryTime.value = comeDate.value.join('/') + " " + comeTime.value.join(':');
            comeTimePicker.value = false;
        };

        //离厂时间
        const leaveTimeConfirm = () => {
            leaveFactoryTime.value = leaveDate.value.join('/') + " " + leaveTime.value.join(':');
            leaveTimePicker.value = false;
        };

        // 是否驾车入厂
        const driveClick = () => {
            if (checked.value == 1) {
                platePicker.value = true;
            } else {
                platePicker.value = false;
            }

        };

        //上传文件之前验证
        //(boolean | undefined | Promise<File | File[] | undefined>) 这个是防止:before-read报红
        const beforeRead = (file, detail) => {
            // console.log("上传前", file);
            // console.log(detail)
            const imgformat = /image\/(png|jpg|jpeg)$/;
            if (!imgformat.test(file.type)) {
                showToast('请上传 jpg/jpeg/png 格式图片');
                return false;
            }
            if (file.size > 15 * 1024 * 1024) {
                showToast('文件大小不能超过 15M');
                return false;
            }
            return true;


            // 此时可以自行将文件上传至服务器
            // return new Promise((resolve) => {
            //     //用这种方式是因为用到了vant3推荐的Compressor 
            //     Promise.all([checkWidthAndHeight(file)]).then(res => {
            //         return new proxy.Compressor(file, {
            //             success: resolve
            //         })
            //     })
            // })

        };
        const afterRead = (file) => {
            // console.log("上传后", file.file);
            file.status = 'uploading';
            file.message = '上传中...';
            //处理上传文件参数
            let fd = new FormData();
            fd.append('file', file.file);
            request({
                url: `/wui/jzhb/fileup_action.jsp`,
                headers: {
                    'Content-Type': 'multipart/form-data'
                },
                method: "post",
                data: fd
            }).then((res) => {
                console.log(res)
                sfzfh.value = res
                if (res.url !== "null") {
                    // console.log(sfz.value)
                    // debugger
                    // sfz.value.push({url: res.url});
                    // console.log(sfz.value)
                   
                    file.status = "done";
                    
                } else {
                    file.status = 'failed';
                    file.message = '上传失败';
                }

            });

        };
        //检查图片的宽高
        const checkWidthAndHeight = (file) => {
            return new Promise((resolve, reject) => {
                var img = new Image();
                img.src = URL.createObjectURL(file);
                img.onload = function () {
                    var width = img.width;
                    var height = img.height;
                    // console.log("当前图片的宽高", width, height);
                    if (width > 500 || height > 695) {
                        showToast('图片分辨率不能超过 500 X 695'); // 图片分辨率不能超过 500 X 695
                        reject(false);
                    } else {
                        resolve(true);
                    }
                }
            })
        }


        // 删除文件
        const sfzdelete = (file, detail) => {
            // console.log("删除数据", file, detail);
            sfz.value.splice(detail.index, 1);
        }
        const onSubmit = (values) => {
            if (incomeValue != '0') {
                if (values.sfzhm == '') {
                    showToast('请输入身份证号码');
                    return false;
                }
            }
            var formData = {};
            formData.incomeValue = incomeValue; //入厂类型 0 客户来访 1 其他来访 2 物资运输
            //将【姓名】转为base64 TODO
            let output1 = Buffer.from(values.sqr, 'utf8')
            formData.username = output1.toString('base64');
            //将【姓名】转为base64 END
            formData.sqr = sqrValue; //姓名
            formData.factory = factoryValue; //厂区 0 金正厂区 1 水环境
            formData.department = departmentValue; //部门id
            //将【来访者姓名】转为base64 TODO
            let output2 = Buffer.from(values.comeName, 'utf8')
            formData.comeName = output2.toString('base64');
            //将【来访者姓名】转为base64 END
            formData.tel = values.tel; //联系电话
            //将【来访单位】转为base64 TODO
            let output4 = Buffer.from(values.comeUnit, 'utf8')
            formData.comeName = output4.toString('base64');
            //将【来访事由】转为base64 END

            //将【来访事由】转为base64 TODO
            let output5 = Buffer.from(values.comeMatter, 'utf8')
            formData.comeName = output5.toString('base64');
            //将【来访事由】转为base64 END

            formData.enterFactoryTime = enterFactoryTime.value; //入厂时间 2022/10/06 12：00
            formData.leaveFactoryTime = leaveFactoryTime.value; //离厂时间 2022/10/06 12：00
            //将【同行人】转为base64 TODO
            let output6 = Buffer.from(values.associated, 'utf8')
            formData.associated = output6.toString('base64');
            //将【同行人】转为base64 END

            formData.sfzhm = values.sfzhm; //身份证号码
            formData.sfz = sfz.value; //身份证 [{url: 'https://fastly.jsdelivr.net/npm/@vant/assets/sand.jpeg',},{url: 'https://fastly.jsdelivr.net/npm/@vant/assets/tree.jpeg',},]
            //将【车牌号】转为base64 TODO
            let output7 = Buffer.from(values.licenseNum, 'utf8')
            formData.licenseNum = output7.toString('base64');
            //将【车牌号】转为base64 END

            //将【物资名称】转为base64 TODO
            let output8 = Buffer.from(values.goods, 'utf8')
            formData.goods = output8.toString('base64');
            //将【物资名称】转为base64 END
            // console.log('submit', formData);
            const toast = showLoadingToast({
                duration: 0, // 持续展示 toast
                message: '提交中...',
                forbidClick: true,
            });
            request({
                url: `/wui/jzhb/visitor_action.jsp`,
                headers: {

                    'Content-Type': 'application/json;charset=utf-8'
                },
                method: "post",
                data: formData
            }).then((res) => {
                closeToast();
                $router.push({ path: '/foreignIntoSuccess' })

                // if (res.url !== "null") {
                //     sfz.value.push({
                //         url: res.url
                //     })
                // }

            });
        };


        return {
            sfzfh,
            departmentValue,
            comeTimePicker,
            comeDate,
            comeTime,
            enterFactoryTime,
            leaveTimePicker,
            leaveDate,
            leaveTime,
            leaveFactoryTime,
            factoryColumns,
            factory,
            factoryValue,
            factoryPicker,
            section,
            sectionPicker,
            sectionColumns,
            platePicker,
            sfzPicker,
            sqr,
            sqrPicker,
            sqrColumns,
            sqrValue,
            sfzhm,
            // checked,
            sfz,
            goods,
            comeName,
            tel,
            licenseNum,
            incomeColumns,
            income,
            incomeValue,
            incomePicker,
            comeUnit,
            associated,
            comeMatter,
            afterRead,
            beforeRead,
            sfzdelete,
            driveClick,
            comeTimeConfirm,
            leaveTimeConfirm,
            onFactoryConfirm,
            onIncomeConfirm,
            onSectionConfirm,
            onSubmit,
            getDepartMent,
            onSqrConfirm,

        };

    },

};

</script>
<style scoped>
.van-doc-demo-block__title {
    margin: 0;
    padding: 32px 16px 16px;
    color: rgb(150, 151, 153);
    font-weight: 400;
    font-size: 14px;
    line-height: 16px;
}

.wrapper {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
}

.block {
    width: 120px;
    height: 120px;
    background-color: #fff;
}
</style>